<template>
  <div>
    <el-card>
      <el-form
        :inline="true"
        :model="form"
        class="demo-form-inline"
        label-position="right"
        ref="ruleFormRef"
        :rules="rules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="栏目" prop="column" required>
              <el-cascader
                :options="columnOption"
                :props="props"
                clearable
                v-model="form.column"
                @change="onChannel"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="button_row">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="oncolumnHtml(ruleFormRef)">
                生成内容页HTML
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { getContentTree } from '@/api/content/contentList.js'
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { getContentStatic, getcontentList } from '@/api/config/staticize.js'
import { ElMessage } from 'element-plus'

const store = useStore()
const userId = store.state.app.user.id
const ruleFormRef = ref()
const contentId = ref([])
const form = ref({
  column: [], // 确保是数组
  startDate: '',
  content: []
})
const rules = reactive({
  column: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择栏目'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})
const props = {
  children: 'children',
  label: 'name',
  value: 'id',
  checkStrictly: true // 确保是布尔类型
}
const columnOption = ref([])

const getList = () => {
  const params = { root: 'source', userId: userId }
  getContentTree({ root: params.root, userId: params.userId }).then((res) => {
    const transArr = res.data.resultlist.map((item) => {
      return {
        id: item.id,
        name: `${item.name}`,
        children: item.children
      }
    })
    columnOption.value = transArr
  })
}

const oncolumnHtml = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      getContentStatic({ contentIds: contentId.value }).then((res) => {
        console.log(res)
        ElMessage.success(res.message)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const onChannel = (value) => {
  const channelID = value[value.length - 1]
  form.value.column = value // 确保更新 form.column 的值
  getcontentList({ channal_id: channelID }).then((res) => {
    contentId.value = res.data
  })
}

getList()
</script>

<style lang="scss" scoped>
.el-card {
  min-height: 600px;
}
.button_row {
  text-align: center;
  margin-top: 30px;
}
</style>
